<?php
/**
 * User: hjd-yao
 * Date: 2019/4/17
 * Time: 13:43
 */

namespace App\Http\Controllers\Shop;


use App\Helpers\SelfResponse;
use App\Http\Controllers\BackendController;
use App\Http\Controllers\Shop\Traits\GoodsTrait;
use App\Models\Shop\ShopBrandModel;
use App\Models\Shop\ShopCategoryModel;
use App\Models\Shop\ShopGoodsAttributeModel;
use App\Models\Shop\ShopGoodsModel;
use App\Models\Shop\ShopGoodsSpecModel;
use App\Models\Shop\ShopTypeModel;
use Illuminate\Http\Request;
use App\Helpers\Search;

class ShopGoodsController extends BackendController
{
    use GoodsTrait;
    public $goodsModel;
    public function __construct()
    {
        $this->goodsModel = new ShopGoodsModel();
    }

    /**
     * @title 商品列表
     * @param Request $request
     * @return View
     */
    public function goods(Request $request,$zone = 1)
    {

        $search = Search::make($request)->bindModel(new ShopGoodsModel())
            ->input('info','名称/标题/描述/关键词','',['symbol'=>'like','field'=>['goods_name','title','description','keywords']])
            ->time('created_at','创建时间')
            ->bindSearchData();

        $model = $search->where();

        if($request->has('info')){
            $info = $request->input('info');
            $model = $model->where(function ($query) use ($info){
                $query->where('goods_name','like','%'.$info.'%')
                    ->orWhere('title','like','%'.$info.'%')
                    ->orWhere('description','like','%'.$info.'%')
                     ->orWhere('keywords','like','%'.$info.'%');
            });
        }

        $list =$model->where('goods_zone',$zone)->whereIn('status',[0,1])->orderBy('sort','desc')->paginate($this->getPerPageNum());
        return view('backend::shop.goods.list',[
            'page_title'=>'商品列表',
            'zone'=>$zone,
            'list'=>$list,
             'search'=>$search
        ]);
    }

    /**
     * @title 下架商品
     * @return View
     */
    public function offShelfGoods()
    {
        $list = $this->goodsModel->whereNotIn('status',[0,1])->paginate($this->getPerPageNum());
        return view('backend::shop.goods.off_goods',[
            'page_title'=>'商品列表',
            'list'=>$list
        ]);
    }

    /**
     * @title 商品详情
     * @param $id
     * @return View
     */
    public function infoGoods($id)
    {
        $info = ShopGoodsModel::find($id);
        $category = ShopCategoryModel::whereIn('id',str2arr($info->category_ids))->pluck('name','id');
        $this->info($info);
        return view('backend::shop.goods.detail',[
            'page_title'=>$info->goods_name.'详细信息',
            'info'=>$info,
            'category'=>$category
        ]);
    }

    /**
     * @title 添加商品
     * @param Request $request
     * @param $zone
     * @return SelfResponse|View
     */
    public function create(Request $request,$zone=1)
    {
        if($request->isMethod('post')){
            $goodsModel = new ShopGoodsModel();
            if(!$goodsModel->addGoods($request,$zone)){
                return SelfResponse::error($goodsModel->getErrorMsg('添加商品失败'));
            }
            return SelfResponse::success('添加商品成功',$this->getJumpUrl($zone));
        }else{
            if(!ShopCategoryModel::first()){
                return redirect()->route('b_ShopCategory_create');
            }
            $brands = ShopBrandModel::init()->showBrands();
            return view('backend::shop.goods.add',[
                'category'=>json_encode(ShopCategoryModel::init()->getTrees()),
                'brands'=>$brands,
                'goods_types'=>ShopTypeModel::where('status',1)->pluck('name','id')->toArray(),
                'zone'=>$zone,
                'page_title'=>'添加'.config('shop.zone')[$zone].'商品'
            ]);
        }
    }

    /**
     * @title 更新商品
     * @param Request $request
     * @param $id
     * @return SelfResponse|View
     */
    public function update(Request $request,$id)
    {
        $goods = ShopGoodsModel::find($id);
        if($request->isMethod('post')){
            $goodsModel = new ShopGoodsModel();
            if(!$goodsModel->edit($request,$id)){
                return SelfResponse::error($goodsModel->getErrorMsg('编辑商品失败'));
            }
            return SelfResponse::success('编辑商品成功',$this->getJumpUrl($goods->goods_zone));
        }else{
            $brands = ShopBrandModel::init()->showBrands();
            $specs = $goods->specs()->select(['title','value'])->get()->toArray();
            $sku = $goods->sku()->select(['stock','price','vip_price','market_price','goods_spec_items'])->get()->toArray();
            return view('backend::shop.goods.edit',[
                'category'=>json_encode(ShopCategoryModel::init()->getTrees()),
                'goods_types'=>ShopTypeModel::where('status',1)->pluck('name','id')->toArray(),
                'brands'=>$brands,
                'goods'=>$goods,
                'specs'=>json_encode($specs),
                'sku'=>json_encode($sku),
                'page_title'=>'编辑商品'
            ]);
        }
    }

    /**
     * @title 修改商品价额
     * @param Request $request
     * @param $id
     * @return SelfResponse|View
     */
    public function updatePrice(Request $request, $id)
    {
        $goods = ShopGoodsModel::find($id);
        if($request->isMethod('post')){
            $goodsModel = new ShopGoodsModel();
            if(!$goodsModel->editPrice($request,$id)){
                return SelfResponse::error($goodsModel->getErrorMsg('编辑价格失败'));
            }
            return SelfResponse::success('编辑价格成功',$this->getJumpUrl($goods->goods_zone));
        }else{
            if($goods->goods_zone == 4){
                return $this->editPrice($goods);
            }
            return view('backend::shop.goods.edit_price',[
                'page_title'=>'修改'.$goods->goods_name.'价格',
                'goods'=>$goods,
            ]);
        }
    }

    /**
     * @title 删除商品
     * @param $id
     * @return SelfResponse
     */
    public function delete($id)
    {
        $info = ShopGoodsModel::find($id);
        if(!$info){
            return SelfResponse::error('商品不存在');
        }
        if(!$info->delete()){
            ShopGoodsSpecModel::where('goods_id',$id)->delete();
            ShopGoodsSpecValueModel::where('goods_id',$id)->delete();
            ShopGoodsAttributeModel::where('goods_id',$id)->delete();
            return SelfResponse::error('商品删除失败');
        }
        return SelfResponse::success('商品删除成功');
    }

    /**
     * @title 活动状态
     * @param $id
     * @param $label
     * @return SelfResponse
     */
    public function switchLabelState($id,$label)
    {
        $field = 'is_'.$label;
        $info = ShopGoodsModel::find($id);
        $info->{$field} = abs($info->{$field}-1);
        if(!$info->save()){
            return SelfResponse::error('失败');
        }
        return SelfResponse::success('成功');
    }

    /**
     * @title 商品上架/下架
     * @param $id
     * @return SelfResponse
     */
    public function upOrDown($id)
    {
        $info = ShopGoodsModel::find($id);
        if(!$info){
            return SelfResponse::error('商品不存在');
        }
        if(!in_array($info->status,[0,1])){
            return SelfResponse::error('商品已永久下架');
        }
        $info->status = abs($info->status-1);
        if(!$info->save()){
            return SelfResponse::error('失败');
        }
        return SelfResponse::success('成功');
    }

    /**
     * @title 商品强制下架
     * @param $id
     * @return SelfResponse
     */
    public function foreverDown($id)
    {
        $info = ShopGoodsModel::find($id);
        if(!$info){
            return SelfResponse::error('商品不存在');
        }
        $info->status = -1;
        if(!$info->save()){
            return SelfResponse::error('下架失败');
        }
        return SelfResponse::success('下架成功');
    }

    /**
     * @title 批量删除商品
     * @param Request $request
     * @return SelfResponse
     */
    public function batchDelete(Request $request)
    {
        $ids = $request->input('ids');
        if (!$ids){
            return SelfResponse::error('请选择要删除的数据');
        }
        if(!ShopGoodsModel::whereIn('goods_id',$ids)->delete()){
            ShopGoodsSpecModel::whereIn('goods_id',$ids)->delete();
            ShopGoodsSpecValueModel::whereIn('goods_id',$ids)->delete();
            ShopGoodsAttributeModel::whereIn('goods_id',$ids)->delete();
            return SelfResponse::error('批量删除失败');
        }
        return SelfResponse::success('批量删除成功','b_ShopGoods_goods');
    }

    private function getJumpUrl($zone)
    {
        if($zone==3){
            $jumpUrl = 'b_ShopGoods_goods';
        }elseif ($zone == 2){
            $jumpUrl = 'b_ShopGoods_goods';
        }else{
            $jumpUrl = 'b_ShopGoods_goods';
        }

        return ['b_ShopGoods_goods',['zone'=>$zone]];
    }
}